//index.js
//获取应用实例
// var app = getApp()
// var util = require('../../utils/util.js')
var area = require('../../utils/area.js')

var areaInfo = [];//所有省市区县数据

var provinces = [];//省

var citys = [];//城市

var countys = [];//区县

var index = [0, 0, 0];

var cellId;

var t = 0;
var show = false;
var moveY = 200;

Page({
  data: {
    show: show,
    provinces: provinces,
    citys: citys,
    countys: countys,
   // streets: streets,
    value: [0, 0, 0],
    array: ['100万以下', '100-150万', '150-200万', '200万-250万', '250-300万', '300万以上'],//售价
    
    hxarray: ['不限', '一室', '二室', '三室', '四室及以上'],
    index: 0, //售价选择
    hxindex: 0, //户型
    showView: true,
    url: getApp().globalData.url, //链接路径
    newlist:[],//新房
    xslist:[], //销售
    xsindex: 0,
    arealist: [], //面积
    areaindex: 0,
  },
  //滑动事件
  bindChange: function (e) {
    var val = e.detail.value
    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      getCityArr(val[0], this);//获取地级市数据
      getCountyInfo(val[0], val[1], this);//获取区县数据
    } else {    //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], this);//获取区县数据
      }
    }
    index = val;
    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      province: provinces[val[0]].name,
      city: citys[val[1]].name,
      county: countys[val[2]].name
    })
  },
  //售价事件
  pricechange: function (e) {
    //console.log(e);
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    var that = this;
    that.setData({
      index: e.detail.value
    });
    selecthouse(that);
  },
  //户型
  hxchange: function (e) {
    //console.log(e);
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    var that = this;
    that.setData({
      hxindex: e.detail.value
    });
    selecthouse(that);
  },
  //销售类型
  xschange: function (e) {
    var that = this;
    that.setData({
      xsindex: e.currentTarget.dataset.xsindex,
      showView: "hide"
    });
    selecthouse(that);
  },
  //面积
  areachange: function (e) {
    var that = this;
    that.setData({
      areaindex: e.currentTarget.dataset.areaindex,
      showView: "hide"
    });
    selecthouse(that);
  },
  onLoad: function (options) {
    showView: (options.showView == "true" ? true : false);
    cellId = options.cellId;
    var that = this;
    var date = new Date();
    //获取省市区县数据
    area.getAreaInfo(function(arr){
      areaInfo = arr;
      //获取省份数据
      //默认获取杭州市的
      getProvinceData(that);
      //初始化调一次
      getCityArr(0, that);
      getCountyInfo(0, 0, that);
    });
    //获取新房信息
    wx.request({
      url: this.data.url + "Smallprogram/Newhouse/index",
      success: function (res) {
        //console.log(res.data);
        for (var i = 0; i < res.data.house.info.list.length; i++) {
          var averageprice = (res.data.house.info.list[i]['price'] / res.data.house.info.list[i]['build_area']).toFixed(2);
          res.data.house.info.list[i]['averageprice'] = averageprice ? averageprice : 0;
          switch (res.data.house.info.list[i]['sell_status']) {
            case "67":
              res.data.house.info.list[i]['sell_name'] = "待售楼盘";
              break;
            case "68":
              res.data.house.info.list[i]['sell_name'] = "在售楼盘";
              break;
            case "69":
              res.data.house.info.list[i]['sell_name'] = "尾盘楼盘";
              break;
            case "70":
              res.data.house.info.list[i]['sell_name'] = "售完楼盘";
              break;
            default:
              res.data.house.info.list[i]['sell_name'] = "暂未定义";
              break;
          }
          /*
          * 物业类型*/
          var propertylList = res.data.house.info.list[i]['property_type'].split(",");
          var property_info = '';

          for (var j = 0; j < propertylList.length; j++) {
            for (var k = 0; k < res.data.property.length; k++) {
              if (propertylList[j] == res.data.property[k]['id']) {
                property_info += res.data.property[k]['title'];
              }
            }
          }
          res.data.house.info.list[i]['property_info'] = property_info ? property_info : "";


          /**
           * 售价
           */
          var array=new Array();
          array[0] = {'id':0,'name':'不限价格'};
          var array_num = 1;
          for(var i = 0;i<res.data.price.length;i++){
            var info = {};
            info['id'] = res.data.price[i]['name'];
            info['name'] = res.data.price[i]['title'];
            array[array_num] = info;
            array_num++;
          }
          
          /**
          * 户型
          */
          var hxarray = new Array();
          hxarray[0] = { 'id': 0, 'name': '不限户型' };
          var hx_num = 1;
          for (var i = 0; i < res.data.property.length; i++) {
            var info = {};
            info['id'] = res.data.property[i]['name'];
            info['name'] = res.data.property[i]['title'];
            hxarray[hx_num] = info;
            hx_num++;
          }
          /*
          * 楼盘特色
          var specialList = res.data.house.info.list[i]['special'].split(",");
          var special_info = '';
          
          for (var j=0; j < specialList.length;j++){
            for (var k=0; k < res.data.special.length; k++) {
              if (specialList[j] == res.data.special[k]['id']){
                special_info += res.data.special[k]['title'];
              }
            }
          }
          res.data.house.info.list[i]['special_info'] = special_info;*/
        }
        //console.log(res.data.house.info);
        
        that.setData({
          newlist: res.data.house.info.list,
          xslist: res.data.sell_status,
          arealist: res.data.area,
          array: array,
          hxarray: hxarray,
        });
       },
    });
  },

  // ------------------- 分割线 --------------------
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    }
    )
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },
  //移动按钮点击事件
  translate: function (e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    // this.animation.translate(arr[0], arr[1]).step();
    animationEvents(this, moveY, show);

  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    //console.log(e);
    selecthouse(this);
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this, moveY, show);
  },
  //关闭隐藏弹窗浮层
  closehiddenFloatView(e) {
    //console.log(e);
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this, moveY, show);

  },
  //页面滑至底部事件
  onReachBottom: function () {
    // Do something when page reach bottom.
  },
  //点击更多
  onChangeShowState: function () {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  //跳转到详情页
  newhouseUrl:function(e){
    wx.navigateTo({
      url: '../newhousedetail/newhousedetail?id=' + e.currentTarget.dataset.id,
    })
  },
  oncloseShowState:function(){
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  }
})

//动画事件
function animationEvents(that, moveY, show) {
  //console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  }
  )
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })

}

// ---------------- 分割线 ---------------- 

//获取省份数据
function getProvinceData(that, area_id) {
  var s;
  provinces = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    s = areaInfo[i];
    if (s.leveltype == "2") {
      provinces[num] = s;
      num++;
    }
  }
  that.setData({
    provinces: provinces
  })  
}

// 获取地级市数据
function getCityArr(count, that, area_id) {
  var c;
  citys = [];
  var num = 0;
  for (var j = 0; j < areaInfo[count]['_child'].length; j++) {
    c = areaInfo[count]['_child'][j];
    citys[num] = c;
    num++;
  }


 /* for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.id == area_id){
      console.log(areaInfo[i]);
      for (var j = 0; j < c['_child'].length; j++) {
        citys[num] = c['_child'][j];
        num++;
      }
    }
  }*/
  if (citys.length == 0) {
    citys[0] = { name: '' };
  }

  that.setData({
    city: "",
    citys: citys,
    value: [count, 0, 0]
  })
}

// 获取区县数据
function getCountyInfo(column0, column1, that) {
  var c;
  countys    = {};
  countys[0] = {id:'0',name :'不限街道'};
  var num = 1;
  for (var i = 0; i < areaInfo[column0]['_child'][column1]['_child'].length; i++) {
    c = areaInfo[column0]['_child'][column1]['_child'][i];
    countys[num] = c;
    num++;
  }
 /*for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.parentid != "0" && c.leveltype == "4") {
      countys[num] = c;
      num++;
    }
  }*/
 
  that.setData({
    county: "",
    countys: countys,
    value: [column0, column1, 0]
  })
}

//根据搜索条件获取房源
function selecthouse(that){
  var pagedata = that.data;
  //区域
  var areasid, street;
  var value = pagedata.value;
  areasid = areaInfo[value[0]]['_child'][value[1]]['id'];//区域ID
  street = value[2] == 0 ? "" : areaInfo[value[0]]['_child'][value[1]]['_child'][value[2] - 1]['id'];
  if (street != "") {
    areasid = '';
  } else {
    street = '';
  }

  //售价
  var price;
  var index = pagedata.index;
  price = pagedata.array[index]['id'];
  
  //户型
  var property;
  var hxindex = pagedata.hxindex;
  property = pagedata.hxarray[hxindex]['id'] ? pagedata.hxarray[hxindex]['id']:"";

  //销售
  var sell_status;
  var xsindex = pagedata.xsindex;
  for (var i = 0; i < pagedata.xslist.length;i++){
    if (pagedata.xslist[i]['id'] == xsindex){
      sell_status = pagedata.xslist[i]['name'];
    }
  }

  //面积
  var build_area;
  var areaindex = pagedata.areaindex;
  for (var i = 0; i < pagedata.xslist.length; i++) {
    if (pagedata.arealist[i]['id'] == areaindex) {
      build_area = pagedata.arealist[i]['title'];
    }
  }
  //console.log(areaInfo[value[0]]['_child'][value[1]]);
 
  //console.log(areasid + " - " + street);
  
  wx.request({
    url: that.data.url + "Smallprogram/Newhouse/index",
    data: {
      areasid: areasid,
      street: street,
      price: price,
      property: property,
      sell_status: sell_status ? sell_status:"",
      build_area: build_area ? build_area : "",
    },
    success: function (res) {
      //console.log("@@");
     // console.log(res.data);
      for (var i = 0; i < res.data.house.info.list.length; i++) {
        var averageprice = (res.data.house.info.list[i]['price'] / res.data.house.info.list[i]['build_area']).toFixed(2);
        res.data.house.info.list[i]['averageprice'] = averageprice ? averageprice : 0;
        switch (res.data.house.info.list[i]['sell_status']) {
          case "67":
            res.data.house.info.list[i]['sell_name'] = "待售楼盘";
            break;
          case "68":
            res.data.house.info.list[i]['sell_name'] = "在售楼盘";
            break;
          case "69":
            res.data.house.info.list[i]['sell_name'] = "尾盘楼盘";
            break;
          case "70":
            res.data.house.info.list[i]['sell_name'] = "售完楼盘";
            break;
          default:
            res.data.house.info.list[i]['sell_name'] = "暂未定义";
            break;
        }
        /*
        * 物业类型*/
        var propertylList = res.data.house.info.list[i]['property_type'].split(",");
        var property_info = '';

        for (var j = 0; j < propertylList.length; j++) {
          for (var k = 0; k < res.data.property.length; k++) {
            if (propertylList[j] == res.data.property[k]['id']) {
              property_info += res.data.property[k]['title'];
            }
          }
        }
        res.data.house.info.list[i]['property_info'] = property_info ? property_info : "";

        /*
        * 楼盘特色
        var specialList = res.data.house.info.list[i]['special'].split(",");
        var special_info = '';
        
        for (var j=0; j < specialList.length;j++){
          for (var k=0; k < res.data.special.length; k++) {
            if (specialList[j] == res.data.special[k]['id']){
              special_info += res.data.special[k]['title'];
            }
          }
        }
        res.data.house.info.list[i]['special_info'] = special_info;*/
      }
      //console.log(res.data.house.info);
      that.setData({
        newlist: res.data.house.info.list,
      });
    },
  });
}
